package com.ruoyi.web.service;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class C2CodeDetailsService {

    @Autowired
    private DruidDataSource druidDataSource;

//    /**
//     * 获取过去30天 `moduleName` 出现次数前30名及其次数 merge (后面的方法和这个效果一致, 暂且注释)
//     *
//     * @return 排序后的前30名数据
//     */
//    public List<Map<String, Object>> getTop30MergeCounts_() {
//        List<Map<String, Object>> result = new ArrayList<>();
//
//        // 获取最近30天的开始和结束时间
//        LocalDateTime now = LocalDateTime.now();
//        LocalDateTime thirtyDaysAgo = now.minusDays(30);
//
//        String startTime = thirtyDaysAgo.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//        String endTime = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//
//        // SQL 查询语句
//        String sql = "SELECT moduleName, COUNT(*) AS count " +
//                "FROM code_merge_info " +
//                "WHERE mergeTime >= ? AND mergeTime < ? " +
//                "GROUP BY moduleName " +
//                "ORDER BY count DESC " +
//                "LIMIT 30";
//
//        try (Connection conn = druidDataSource.getConnection();
//             PreparedStatement stmt = conn.prepareStatement(sql)) {
//
//            // 设置查询参数
//            stmt.setString(1, startTime);
//            stmt.setString(2, endTime);
//
//            // 执行查询并处理结果
//            try (ResultSet rs = stmt.executeQuery()) {
//                while (rs.next()) {
//                    Map<String, Object> data = new HashMap<>();
//                    data.put("moduleName", rs.getString("moduleName"));
//                    data.put("count", rs.getInt("count"));
//                    result.add(data);
//                }
//            }
//        } catch (SQLException e) {
//            e.printStackTrace();
//        }
//
//        return result;
//    }


    /**
     * 获取过去30天 `moduleName` 出现次数前30名及其次数 commit
     *
     * @return 排序后的前30名数据
     */
    public List<Map<String, Object>> getTop30CommitCounts() {
        List<Map<String, Object>> result = new ArrayList<>();

        // SQL 查询语句
        String sql = "SELECT moduleName, COUNT(*) AS count " +
                "FROM code_commit_info " +
                "WHERE mergeTime >= DATE_SUB(NOW(), INTERVAL 30 DAY) " + // 筛选最近30天的数据
                "GROUP BY moduleName " +
                "ORDER BY count DESC " +
                "LIMIT 30";  // 获取前30条数据

        try (Connection conn = druidDataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            // 执行查询并处理结果
            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    Map<String, Object> data = new HashMap<>();
                    data.put("moduleName", rs.getString("moduleName"));
                    data.put("count", rs.getInt("count"));
                    result.add(data);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 获取过去30天 `moduleName` 出现次数前30名及其次数 merge
     *
     * @return 排序后的前30名数据
     */
    public List<Map<String, Object>> getTop30MergeCounts() {
        List<Map<String, Object>> result = new ArrayList<>();

        // 获取最近30天的开始和结束时间
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime thirtyDaysAgo = now.minusDays(30);

        String startTime = thirtyDaysAgo.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String endTime = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        // SQL 查询语句
        String sql = "SELECT moduleName, COUNT(*) AS count " +
                "FROM code_merge_info " +
                "WHERE mergeTime >= ? AND mergeTime < ? " +
                "GROUP BY moduleName " +
                "ORDER BY count DESC " +
                "LIMIT 30";

        try (Connection conn = druidDataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            // 设置查询参数
            stmt.setString(1, startTime);
            stmt.setString(2, endTime);

            // 执行查询并处理结果
            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    Map<String, Object> data = new HashMap<>();
                    data.put("moduleName", rs.getString("moduleName"));
                    data.put("count", rs.getInt("count"));
                    result.add(data);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return result;
    }


    /**
     * 获取过去30天 `moduleName` 出现次数前30名commit次数、merge次数、merge失败次数、merge成功次数、tag成功次数
     *
     * @return 排序后的前30名数据
     */
    public List<Map<String, Object>> getTop30CodeDetails() {
        List<Map<String, Object>> result = new ArrayList<>();

        // 调用现有方法获取 Top30 数据
        List<Map<String, Object>> top10CommitCounts = getTop30CommitCounts();

        // 获取最近30天的开始和结束时间
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime thirtyDaysAgo = now.minusDays(30);

        String startTime = thirtyDaysAgo.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String endTime = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        // SQL 查询语句
        String releaseCountSql = "SELECT COUNT(*) AS tagCount " +
                "FROM module_release_his_info " +
                "WHERE moduleName = ? AND fullName = ? " +
                "AND modifyTime >= ? AND modifyTime < ?";

        String mergeTimesSql = "SELECT COUNT(*) AS mergeCount " +
                "FROM code_merge_info " +
                "WHERE moduleName = ? " +
                "AND mergeTime >= ? AND mergeTime < ?";

        String mergeFailedSql = "SELECT COUNT(*) AS mergeFailedCount " +
                "FROM code_merge_info " +
                "WHERE moduleName = ? " +
                "AND status = 1 " +
                "AND mergeTime >= ? AND mergeTime < ?";

        String mergeSuccessSql = "SELECT COUNT(*) AS mergeSuccessCount " +
                "FROM code_merge_info " +
                "WHERE moduleName = ? " +
                "AND status = 0 " +
                "AND mergeTime >= ? AND mergeTime < ?";

        try (Connection conn = druidDataSource.getConnection();
             PreparedStatement releaseStmt = conn.prepareStatement(releaseCountSql);
             PreparedStatement mergeStmt = conn.prepareStatement(mergeTimesSql);
             PreparedStatement mergeFailedStmt = conn.prepareStatement(mergeFailedSql);
             PreparedStatement mergeSuccessStmt = conn.prepareStatement(mergeSuccessSql)) {

            for (Map<String, Object> item : top10CommitCounts) {
                String moduleNameFull = (String) item.get("moduleName");
                int commitCount = (int) item.get("count");

                // 分割 moduleName 为两部分
                String[] parts = moduleNameFull.split("-");
                if (parts.length == 2) {
                    String moduleName = parts[0];
                    String fullName = parts[1];

                    // 查询 tagCount
                    releaseStmt.setString(1, moduleName);
                    releaseStmt.setString(2, fullName);
                    releaseStmt.setString(3, startTime);
                    releaseStmt.setString(4, endTime);

                    int tagCount = 0;
                    try (ResultSet rs = releaseStmt.executeQuery()) {
                        if (rs.next()) {
                            tagCount = rs.getInt("tagCount");
                        }
                    }

                    // 查询 mergeCount
                    mergeStmt.setString(1, moduleNameFull);
                    mergeStmt.setString(2, startTime);
                    mergeStmt.setString(3, endTime);

                    int mergeCount = 0;
                    try (ResultSet rs = mergeStmt.executeQuery()) {
                        if (rs.next()) {
                            mergeCount = rs.getInt("mergeCount");
                        }
                    }

                    // 查询 mergeFailedCount
                    mergeFailedStmt.setString(1, moduleNameFull);
                    mergeFailedStmt.setString(2, startTime);
                    mergeFailedStmt.setString(3, endTime);

                    int mergeFailedCount = 0;
                    try (ResultSet rs = mergeFailedStmt.executeQuery()) {
                        if (rs.next()) {
                            mergeFailedCount = rs.getInt("mergeFailedCount");
                        }
                    }

                    // 查询 mergeSuccessCount
                    mergeSuccessStmt.setString(1, moduleNameFull);
                    mergeSuccessStmt.setString(2, startTime);
                    mergeSuccessStmt.setString(3, endTime);

                    int mergeSuccessCount = 0;
                    try (ResultSet rs = mergeSuccessStmt.executeQuery()) {
                        if (rs.next()) {
                            mergeSuccessCount = rs.getInt("mergeSuccessCount");
                        }
                    }

                    // 构建最终结果
                    Map<String, Object> data = new HashMap<>();

                    // 分割 moduleNameFull 为两部分
                    String dealModuleName = moduleNameFull; // 默认使用完整名称
                    String responsiblePerson = "";     // 默认负责人为空

                    String[] partsOne = moduleNameFull.split("-");
                    if (partsOne.length == 2) {
                        dealModuleName = partsOne[0];
                        responsiblePerson = partsOne[1];
                    }

                    data.put("moduleName", dealModuleName);                // 存入模块名
                    data.put("responsiblePerson", responsiblePerson);        // 存入负责人
                    data.put("commitCount", commitCount);
                    data.put("tagCount", tagCount);
                    data.put("mergeCount", mergeCount);
                    data.put("mergeFailedCount", mergeFailedCount);
                    data.put("mergeSuccessCount", mergeSuccessCount);

                    result.add(data);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }
}
